package com.tian.plugtool.word;

import com.tian.common.config.TianYaConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.util.UUID;

public class WordByFreeMarker<T> {
    private static final Logger logger = LogManager.getLogger(WordByFreeMarker.class);
    private static String path = new File(WordByFreeMarker.class.getClassLoader().getResource("ftls").getFile()).getPath();

    /**
     * 实体对象
     */
    public Class<T> clazz;

    public WordByFreeMarker(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * 生成word
     */
    public String CreateWord(T data, String template, String filename) throws IOException, TemplateException {
        //输出文档路径及名称
        Writer out = null;
        FileOutputStream fos = null;
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        try {
            // 渲染模板
            //cfg.setDirectoryForTemplateLoading(new File(path));
            cfg.setClassForTemplateLoading(this.getClass(), "/ftls");
            //cfg.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/ftls"));
            // java对象数据传递到模板文件ftl
            Template tpl = cfg.getTemplate(template, "UTF-8");//"UTF-8"

            filename = encodingFilename(filename);
            File outFile = new File(getAbsoluteFile(filename));
            fos = new FileOutputStream(outFile);
            OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
            out = new BufferedWriter(oWriter);
            // 填充数据
            StringWriter writer = new StringWriter();
            tpl.process(data, out);
            return filename;
        } catch (IOException e) {
            logger.error("渲染模板失败：", e);
            throw e;
        } catch (TemplateException e) {
            logger.error("渲染模板失败", e);
            throw e;
        } finally {
            if (out != null) {
                try {
                    out.close();
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

    /**
     * 编码文件名
     */
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".doc";
        return filename;
    }

    /**
     * 设置文件路径
     *
     * @param filename
     * @return
     */
    public String getAbsoluteFile(String filename) {
        String downloadPath = TianYaConfig.getExcelPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
